package controller

import (
	"appengine"
	"entity"
	"fmt"
	"funcMap"
	"html/template"
	"model"
	"net/http"
	"strconv"
	"strings"
)

func Category(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	c.Infof("Calling category.go")
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	strCate := r.URL.Path
	strCate = strings.Replace(strCate, "/category/", "", -1)

	//Get setting
	var setting entity.Setting
	if err := model.GetCurrentSetting(c, &setting); err != nil {
		fmt.Fprintln(w, "Look like you just start this application, please come admin page to setting your page !")
		return
	}

	//Get template
	var currentTemplate entity.Template
	if err := model.GetTemplate(c, setting.CurrentTemplateID, &currentTemplate); err != nil {
		fmt.Fprintln(w, "Look like you just start this application, no template avaiable ! Please come admin page to setting your page !")
		return
	}

	//Get category
	var category entity.Category
	if err := model.GetCategory(c, strCate, &category); err != nil {
		fmt.Fprintln(w, "This category is not exist or has been deleted !")
		return
	}

	//Page handle
	pagePara := r.FormValue("page")
	var page int
	if i, err := strconv.Atoi(pagePara); err != nil {
		page = 1
	} else {
		if i > 0 {
			page = i
		}
	}

	//Get News
	var listNews []entity.News
	//Get all tag relationship by tag alias : strTag
	arrCategoryRelationship, err := model.ListCategoryRelationshipByTagAlias(c, strCate, page)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	} else {
		var arrNewsAlias []string
		for _, e := range arrCategoryRelationship {
			arrNewsAlias = append(arrNewsAlias, e.NewsAlias)
		}
		//Get multi news by id
		listNews, err = model.GetMultiNews(c, arrNewsAlias)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

	//Get recent view
	recent, err := model.ListRecentNews(c)
	if err != nil {
		c.Errorf("Error when get Recent View at Homepage !")
	}

	//Get list category
	listCategory, err := model.ListCategory(c)
	if err != nil {
		c.Errorf("Error when get List Category at Homepage !")
	}

	//Get tag pool
	tagPool, err := model.TagPool(c)
	if err != nil {
		c.Errorf("Error when get Tag Pool at Homepage !")
	}

	//Check if have next page
	var hasNextPage bool = false
	var hasPreviousPage bool = false
	var nextPage int = 0
	var previousPage int = 0
	if len(listNews) > model.NewsLimit {
		hasNextPage = true
		nextPage = page + 1
		listNews = listNews[0 : len(listNews)-1]
	}
	if page > 1 {
		hasPreviousPage = true
		previousPage = page - 1
	}

	//Add function to view
	funcMap := template.FuncMap{
		"GetYear":      funcMap.GetYear,
		"GetMonth":     funcMap.GetMonth,
		"GetMonthName": funcMap.GetMonthName,
		"GetDay":       funcMap.GetDay,
		"GetCategory":  funcMap.GetCategoryNews,
	}

	//Add data to template
	data := map[string]interface{}{
		"category":        category,
		"listNews":        listNews,
		"page":            page,
		"hasNextPage":     hasNextPage,
		"nextPage":        nextPage,
		"hasPreviousPage": hasPreviousPage,
		"previousPage":    previousPage,
		"listCategory":    listCategory,
		"tagPool":         tagPool,
		"recent":          recent,
		"setting":         setting,
		"domainName":      r.Host,
	}

	t := template.Must(template.New("Category").Funcs(funcMap).Parse(currentTemplate.Category))
	err = t.Execute(w, data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
